package com.yq.cp.utils;
import com.alibaba.excel.EasyExcel;
import com.yq.cp.config.MyException;
import com.yq.cp.servlet.ServletSupport;
import lombok.Builder;
import lombok.Data;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

@Data
@Builder
public class ExcelUtil {

    public static <T> void doWrite(String fileName, String sheet, Class<T> type, List<T> list) {
        try {
            if (StringUtil.isEmpty(fileName)) {
                fileName = "export";
            }
            // 设置文件和响应
            HttpServletResponse response = ServletSupport.getResponse();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "utf-8"));
            response.setHeader("Cache-Control", "No-cache");
            response.flushBuffer();
            EasyExcel.write(response.getOutputStream(), type).sheet(sheet).doWrite(list);
        } catch (Exception e) {
            throw new MyException("导出Excel异常[" + e.getMessage() + "]");
        }
    }

}
